<script lang="ts" setup>
import { ref } from 'vue';
import { apikeyService } from '@/service';
import ApikeyDialog from '@/views/user/apikey/ApikeyDialog.vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const pageNum = ref(1);
const pageSize = ref(10);
const dataTotal = ref(0);
const dataRows = ref<Record<string, any>[]>([]);
const loading = ref(false);
const apikeyDialogRef = ref();

// 初始加载
queryApikeyPage();

async function queryApikeyPage() {
  loading.value = true;
  const params = {
    pageSize: pageSize.value,
    pageNum: pageNum.value,
  };
  const res = await apikeyService.queryApikeyPage(params);
  if (res.success) {
    dataTotal.value = res.total;
    dataRows.value = res.result;
  }
  loading.value = false;
}

function openApikeyAdd() {
  apikeyDialogRef.value.open();
}

async function addApikeyItem(row: any) {
  const res = await apikeyService.addApikey(row);
  if (res.success) {
    ElMessage({ type: 'success', message: '新建成功' });
    await queryApikeyPage();
  } else {
    ElMessage({ type: 'error', message: res.errorMsg });
  }
}

function deleteApikey(row: any){
  console.log(row);
  ElMessageBox.confirm(`确定删除'${row.apiKeyName}'密钥吗?`, '操作确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteApikeyItem(row.id);
    })
    .catch(() => {});
}

async function deleteApikeyItem(apikeyId: number) {
  const res = await apikeyService.deleteApikey(apikeyId);
  if (res.success) {
    ElMessage({ type: 'success', message: '删除成功' });
    await queryApikeyPage();
  } else {
    ElMessage({ type: 'error', message: res.errorMsg });
  }
}

</script>


<template>
  <div class="page-api-key">
    <el-container class="table-container">
      <el-header class="page-header">
        <el-button type="primary" @click="openApikeyAdd">新建</el-button>
      </el-header>
      <el-main class="page-body">
        <el-table :data="dataRows">
          <el-table-column prop="apiKeyName" label="密钥名称" width="200" show-overflow-tooltip />
          <el-table-column prop="apiKey" label="密钥" width="350" />
          <el-table-column prop="apiKeyDesc" label="密钥描述"  show-overflow-tooltip/>
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="deleteApikey(scope.row)"> 删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="table-pagination">
          <el-pagination
            :currentPage="pageNum"
            :pageSize="pageSize"
            background
            layout="total, prev, pager, next"
            :total="dataTotal"
            @currentChange="(val: number) => $emit('pageChange', val)"
          />
        </div>
      </el-main>
    </el-container>
    <ApikeyDialog ref="apikeyDialogRef" @add="addApikeyItem"/>
  </div>
</template>

